﻿using Prism.Mvvm;
using Compass.Wasm.Shared.Identities;
using Compass.Update;
using Compass.Wpf.ApiServices;

namespace Compass.Wpf.ViewModels.Dialogs;

public class LoginViewModel : BindableBase, IDialogAware
{
    #region ctor
    private readonly ILoginService _loginService;//事件聚合器，消息提示
    private readonly IEventAggregator _aggregator;
    private readonly IPreferenceService _preferenceService;
    public LoginViewModel(IContainerProvider provider)
    {
        _loginService = provider.Resolve<ILoginService>();
        _aggregator = provider.Resolve<IEventAggregator>();
        _preferenceService=provider.Resolve<IPreferenceService>();
        
        //使用记住的用户名和密码
        var userName = _preferenceService.Get(Consts.UserName);
        var password= _preferenceService.Get(Consts.Password,"123");
        Token = _preferenceService.Get(Consts.Token);

        UserName = string.IsNullOrEmpty(userName) ? Environment.UserName : userName;//如果是空的那么使用当前计算机登录用户
        Password = string.IsNullOrEmpty(password) ? "123" : password;//如果是空的那么使用默认密码123

        ExecuteCommand =new DelegateCommand<string>(Execute);
    }
    #endregion

    #region 属性
    public string Title { get; } = "Compass";
    
    private string userName;
    public string UserName
    {
        get => userName;
        set { userName = value; RaisePropertyChanged(); }
    }
    private string password;
    public string Password
    {
        get => password;
        set { password = value; RaisePropertyChanged(); }
    }

    public string? Token { get; set; }

    
    #endregion

    public event Action<IDialogResult>? RequestClose;
    public DelegateCommand<string> ExecuteCommand { get; }
    
    private void Execute(string obj)
    {
        switch (obj)
        {
            case "Login": Login(); break;
            case "Logout": Logout(); break;
        }
    }

    /// <summary>
    /// 登录操作
    /// </summary>
    private async void Login()
    {
        CheckUpdate();
        if (string.IsNullOrWhiteSpace(UserName) || string.IsNullOrWhiteSpace(Password))
            return;
        var loginResult = await _loginService.LoginAsync(new UserDto
        {
            UserName = this.UserName,
            Password = this.Password
        });
        if (loginResult!=null && loginResult.Status)
        {
            _preferenceService.Set(Consts.UserId, loginResult.Result.Id.ToString());
            _preferenceService.Set(Consts.UserName, UserName);
            _preferenceService.Set(Consts.Password, Password);
            _preferenceService.Set(Consts.Role, loginResult.Result.Role);
            AppSession.Roles = loginResult.Result.Role;

            _aggregator.SendMessage("登录成功，欢迎使用Compass！");//默认即发到主页
            RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
            return;
        }
        //登录失败提示...
        _aggregator.SendMessage(loginResult.Message, Filter_e.Login);
    }


    /// <summary>
    /// 退出操作
    /// </summary>
    private void Logout()
    {
        RequestClose?.Invoke(new DialogResult(ButtonResult.No));
    }

    //检查更新
    private void CheckUpdate()
    {
        var updateMgr = new UpdateManager();
        if (!updateMgr.NeedUpdate) return;
        Logout();
        //启动升级程序
        System.Diagnostics.Process.Start("Compass.Update.exe");
    }
    
    public bool CanCloseDialog()
    {
        return true;
    }
    public void OnDialogClosed()
    {
        Logout();
    }
    public void OnDialogOpened(IDialogParameters parameters)
    {

    }
}